<?php
namespace Home\Service;

use Think\Service\BasicService;

class OrderService extends BasicService {
    public function insert($model) {
        return $this->db->add($model);
    }

    public function AddAll($model) {
        $data = $this->db->addAll($model);
        return $data;
    }

    public function remove($condition) {
        return $this->db->where($condition)->delete();
    }

    public function update($where, $model = array()) {
        return $this->db->where($where)->save($model);
    }

    public function find($condition) {
        return $this->db->where($condition)->find();
    }

    public function query($condition, $limit = array(), $field = '*', $order = '', $join = '') {
        $data = $this->db->join($join)->where($condition)->field($field)->limit($limit['start'], $limit['end'])->order($order)->select();
        return $data;
    }

    public function count($condition) {
        return $this->db->where($condition)->count();
    }

    /*
     * 生成订单
     * 添加订单主表
     * 添加订单书籍表
     * 修改书籍库存
     * 修改规格库存
     * 使用优惠劵
     * 计算邮费
     * 计算是否有书籍存在包邮
     * 此时书籍是不出库的
     */
    public function AddOrder($data, $OID) {
        $bookNum = 0;//书籍本书
        $orderMoney = 0;//书籍售价
        $orderOldMoney = 0;//书籍原价
        $BookIds = array();//保存书籍id用于计算是否存在书籍存在包邮
        $this->db->startTrans();
        $this->db = M('card_log');
        //是否有使用优惠劵
        $YHQ_MONEY = $this->GetCardMoney($data['card_id']);

        //生成订单书籍表
        $order_books = array();
        $temp = json_decode($data['books'], true);
        foreach ($temp as $k => $v) {
            $fields = 'ts_book.ID as BID,
            ts_book.PIC_URL as BPIC_URL,
            ts_book.Y_PRICE as BY_PRICE ,
            ts_book.TITLE as BNAME,
            ts_book.STOCK as STOCK,
            ts_book_gg.*';
            $bookInfo = M('book')->join('ts_book_gg on ts_book_gg.BOOK_ID = ts_book.ID')->where(array('ts_book_gg.ID' => $v['book_gg_id']))->field($fields)->find();
            $order_book['ob_id'] = 'WXOBID_' . uniqid() . rand(10, 99);//订单书籍ID
            $order_book['order_id'] = $OID;//订单id
            $order_book['book_id'] = $bookInfo['BID'];//书籍ID
            $order_book['book_gg_id'] = $bookInfo['ID'];//书籍规格id
            $order_book['ob_name'] = $bookInfo['BNAME'];//书籍名字
            $order_book['ob_book_gg'] = $bookInfo['GG_NAME'];//书籍规格名称
            $order_book['ob_old_money'] = $bookInfo['BY_PRICE'];//书籍原价
            $order_book['ob_pay_money'] = $bookInfo['GG_PRICE'];//书籍售价
            $order_book['ob_num'] = $v['num'];//购买数量
            $bookNum += $v['num'];//总书籍本书
            $order_book['ob_book_pic'] = $bookInfo['BPIC_URL'];//书籍图片
            $order_book['isbn'] = $bookInfo['isbn'];//书籍图片
            $orderMoney += ($bookInfo['GG_PRICE'] * $v['num']);
            $orderOldMoney += ($bookInfo['BY_PRICE'] * $v['num']);
            $order_books[] = $order_book;
            $BookIds[] = $order_book['book_id'];
            //修改规格库存
            $ggNUM = $bookInfo['NUM'] - $v['num'];
            //修改书籍库存
            $bookNUM = $bookInfo['STOCK'] - $v['num'];
            if ($ggNUM >= 0) {
                $this->db = M('book_gg');
                $kcOK = $this->db->where(array('ID' => $v['book_gg_id']))->save(array('NUM' => $ggNUM));
                $this->db = M('book');
                $bkcOK = $this->db->where(array('ID' => $bookInfo['BID']))->save(array('STOCK' => $bookNUM));
                if (!$kcOK || !$bkcOK) {
                    $this->db->rollback();
                    return -3;//库存修改失败
                }
            } else {
                $this->db->rollback();
                return -2;//库存不足
            }


        }
        $this->db = M('order_book');
        $addbookOK = $this->db->addAll($order_books);
        //生成订单书籍表成功
        if ($addbookOK) {
            $orderSave['order_id'] = $OID;//订单ID
            $orderSave['user_id'] = $data['user_id'];//用户id
            $orderSave['order_phone'] = $data['order_phone'];//	手机号码（当提交订单的时候直接录入）
            $orderSave['order_address_name'] = $data['order_address_name'];//订单收货人姓名
            $orderSave['order_address'] = $data['order_address'];//订单的完整地址
            $orderSave['order_adderss_province'] = $data['order_adderss_province'];//订单地址的省份
            $orderSave['order_adderss_city'] = $data['order_adderss_city'];//订单地址的城市
            $orderSave['order_adderss_area'] = $data['order_adderss_area'];//订单地址的区
            $orderSave['order_adderss_info'] = $data['order_adderss_info'];//订单的详细地址
            $orderSave['order_num'] = $bookNum;//	订单中的书籍总数
            $orderSave['order_old_money'] = $orderOldMoney;//	所有书籍的原价总和
            $orderSave['order_code'] = 'O_' . time() . rand(0, 9);//	订单编号
            $orderSave['order_start_time'] = date('Y-m-d H:i:s');//	订单开始时间
            $orderSave['order_end_time'] = date('Y-m-d H:i:s', time() + 7 * 24 * 60 * 60);//	结束时间
            $orderSave['order_pay_type'] = $data['order_pay_type']?$data['order_pay_type']:1;//	支付方式（1：微信，2：支付宝）
            $orderSave['order_leixing'] = 2;//	订单的类型 1：租借的订单2：购买的订单
            $orderSave['order_type'] = 1;//	订单状态 1 代付款
            $orderSave['order_discuss_status'] = 2;//	订单的评论的状态：1：评论过了2：未评论
            $orderSave['coupon_id'] = $data['card_id'];//		使用过的优惠券id
            $orderSave['order_user_remarks'] = $data['order_user_remarks'];//订单备注
            $orderSave['order_book_money'] = $orderMoney;//订单所有书籍支付总价
            $orderSave['order_yh_money'] = $YHQ_MONEY;//订单所有书籍支付总价
            $orderMoney -= $YHQ_MONEY;//订单总金额减去优惠劵价格
            //邮费情况
            $YF_MONEY = $this->GetPostage($orderSave['order_address'], $orderMoney, $BookIds);
            $orderSave['order_postage'] = $YF_MONEY;
            $orderMoney += $YF_MONEY;//订单总金额加上邮费
            $orderSave['order_money'] = $orderMoney;//	订单总金额
            $this->db = M('order');
            $addorderOK = $this->db->add($orderSave);
            if ($addorderOK) {
                $this->db->commit();
                return 1;
            } else {
                $this->db->rollback();
                return -4;//订单主表添加失败
            }

        } else {
            $this->db->rollback();
            return -5;//订单书籍添加失败
        }

    }


    /*
     * 获取用户所有订单
     */
    public function GetAllOrder($where, $limit) {
        $order_data = $this->db->where($where)->limit($limit['start'], $limit['end'])->order('order_start_time DESC')->select();
        foreach ($order_data as $k => $v) {
            $order_book = $this->db->join('ts_order_book on ts_order_book.order_id = ts_order.order_id ')//                ->join('ts_book on ts_book.ID = ts_order_book.book_id ')
            ->field('ts_order_book.*')->where(array('ts_order.order_id' => $v['order_id']))->select();
            $order_data[$k]['bookdatas'] = $order_book;
        }
        return $order_data;
    }

    /*
     * 获取订单详情
     */
    public function GetOrderData($where) {
        $order_data = $this->db->where($where)->find();
        $order_book = M('order_book')->where(array('order_id' => $order_data['order_id']))->select();
        $order_data['bookdatas'] = $order_book;
        return $order_data;

    }

    /*
     * 取消订单与伪删除订单
     * 库存回退
     * 参数订单id
     */
    public function rollbackBookNum($order_id) {
        $this->db->startTrans();
        $this->db = M('order_book');
        $data = $this->db->where(array('order_id' => $order_id))->select();
        $OK = 1;
        foreach ($data as $k => $v) {
            $this->db = M('book_gg');
            $data1 = $this->db->where(array('ID' => $v['book_gg_id']))->find();
            $OK1 = $this->db->where(array('ID' => $v['book_gg_id']))->save(array('NUM' => ($data1['NUM'] + $v['ob_num'])));
            if ($OK1) {
                $this->db = M('book');
                $data2 = $this->db->where(array('ID' => $v['book_id']))->find();
                $OK2 = $this->db->where(array('ID' => $v['book_id']))->save(array('STOCK' => ($data2['STOCK'] + $v['ob_num'])));
                if (!$OK2) {
                    $OK = 0;
                }
            } else {
                $OK = 0;
            }
        }
        if ($OK) {
            $this->db->commit();
            return 1;
        } else {
            $this->db->rollback();
            return 0;
        }

    }

    /*
     * $address地址
     * $money订单所有书籍销售价格、
     * $bookId书籍ID，用于计算是否存在包邮
     * 获取邮费
     */
    public function GetPostage($address, $money, $bookId) {
        $BYB_LS = Service('M', 'by_book');
        $where['BOOK_ID'] = array('in',
            $bookId);
        $BYB_OK = $BYB_LS->query($where);
        //存在书籍包邮
        if ($BYB_OK) {
            return 0;
        }
        $YF_LS = Service('M', 'postage');
        $YF_Data = $YF_LS->find(array('STATE' => 1));
        //满足金额包邮
        if ($money >= $YF_Data['BY_PRICE']) {
            return 0;
        } else {
            return is_int(strpos($address, '广东省')) == false ? $YF_Data['W_PRICE'] : $YF_Data['N_PRICE'];
        }

    }

    /*
     * 由优惠劵id
     * 获取优惠金额
     */
    public function GetCardMoney($card_id) {
        if ($card_id) {
            $this->db = M('card_log');
            $this->db->startTrans();
            $yhdata = $this->db->join('ts_card on ts_card.ID = ts_card_log.CARD_ID')->where(array('ts_card_log.ID' => $card_id))->find();
            //优惠劵是否存在
            if ($yhdata) {
                //优惠劵使用状态修改
                $yhupdateOK = $this->db->where(array('ID' => $card_id))->save(array('STATE' => 0));
                //优惠劵使用成功
                if ($yhupdateOK) {
                    $this->db->commit();
                    return $yhdata['ZS_MONEY'];
                } else {
                    $this->db->rollback();
                    return 0;//优惠劵修改失败
                }
            } else {
                $this->db->rollback();
                return 0;//优惠劵不存在
            }
        } else {
            return 0;//无使用优惠劵
        }
    }
}


?>